package com.yj.spring.charpter04;

import cn.hutool.core.collection.CollUtil;
import com.yj.spring.common.ArgumentValue;
import com.yj.spring.common.PropertyValue;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

public class XmlBeanDefinitionReader {

    SimpleBeanFactory beanFactory;

    public XmlBeanDefinitionReader(SimpleBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public void loadBeanDefinitions(Resource resource) {
        while (resource.hasNext()) {
            Element element = (Element) resource.next();
            String id = element.attributeValue("id");
            String className = element.attributeValue("class");

            List<Element> constructorElements = element.elements("constructor-arg");
            List<ArgumentValue> argumentValues = new ArrayList<>();
            if (CollUtil.isNotEmpty(constructorElements)){
                for (Element constructorElement : constructorElements) {
                    String name = constructorElement.attributeValue("name");
                    String value = constructorElement.attributeValue("value");
                    String type = constructorElement.attributeValue("type");

                    argumentValues.add(new ArgumentValue(name, value, type));
                }
            }

            List<Element> propertyElements = element.elements("property");
            List<PropertyValue> propertyValues = new ArrayList<>();
            if (CollUtil.isNotEmpty(propertyElements)){
                for (Element propertyElement : propertyElements) {
                    String name = propertyElement.attributeValue("name");
                    String value = propertyElement.attributeValue("value");
                    String type = propertyElement.attributeValue("type");
                    String ref =  propertyElement.attributeValue("ref");
                    propertyValues.add(new PropertyValue(name, value, type, ref));
                }
            }

            BeanDefinition beanDefinition = new BeanDefinition(id, className);
            beanDefinition.setArgumentValues(argumentValues);
            beanDefinition.setPropertyValues(propertyValues);

            beanFactory.registerBeanDefinition(id, beanDefinition);
        }
    }
}
